#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.shortcuts import render,redirect
from app01.forms import account
from app01 import models

def login(request):
    obj = account.LoginForm(request.POST)
    if request.method=='POST':
        if obj.is_valid():
            all_data=obj.clean()
            if models.User.objects.filter(**all_data):
                request.session['is_login']=True
                return redirect('/index/')
            else:
                return render(request,'account/login.html',{'obj':obj,'error':'密码不对'})
        else:
            error=obj.errors
            return render(request,'account/login.html',{'obj':obj,'error':error})
    return render(request,'account/login.html',{'obj':obj})

def reg(request):
    obj = account.RegForm(request.POST)
    if request.method == "POST":

        if obj.is_valid():
            all_data = obj.clean()
            #####################上传头像#####################
            if request.FILES:
                upload_file = request.FILES
                file_obj = upload_file.get('file')
                file_path = 'photo/'+file_obj.name
                with open(file_path,'wb') as fw:
                    for part in file_obj.chunks():
                        fw.write(part)
                all_data['file']=file_path
            ######################其它数据#####################
            models.User.objects.create(**all_data)
            return redirect('/login/')
        else:
            error = obj.errors
            return render(request,'account/reg.html',{'obj':obj,'error':error})

    return render(request,'account/reg.html',{'obj':obj})

